package com.jianneng.jdg.model.homeactivity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import com.example.com.jianneng.jdg.R;
import com.jianneng.jdg.common.until.Bimp;
import com.jianneng.jdg.common.until.FileUtils;
import com.jianneng.jdg.model.adapter.ConstributeAdapter;
import com.jianneng.jdg.model.view.HorizontalListView;

public class ContributeActivity extends BaseActivity implements
		OnItemClickListener,OnGestureListener{
	private HorizontalListView gridview;
	public List<Bitmap> bmp = new ArrayList<Bitmap>();// 图片List
	private ConstributeAdapter adapter;
	public List<String> drr = new ArrayList<String>();
	private ImageView mAddImage;
	private EditText mContent;
	private TextView mCommit;
	private LinearLayout mBack;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_contribute);
		initView();
		adapter = new ConstributeAdapter(this);
		adapter.setList(bmp);
		adapter.notifyDataSetChanged();
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(this);
	}

	private void initView() {
		gridview = (HorizontalListView) findViewById(R.id.noScrollgridview);
		mAddImage = (ImageView) findViewById(R.id.add_image);
		mContent = (EditText) findViewById(R.id.constribute_edite);
		mCommit = (TextView) findViewById(R.id.constribute_commit);
		mBack = (LinearLayout) findViewById(R.id.contribute_back);
		// 设置点击gridview的背景色
	//	gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mCommit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Editable content = mContent.getText();
				if(content!=null){
					
					Toast.makeText(ContributeActivity.this, content.toString(), 1).show();
				}
				Intent intent = new Intent(ContributeActivity.this, MainActivity.class);
				intent.putExtra("id", "3");
				startActivity(intent);
				ContributeActivity.this.finish();
				
			}
		});
		mBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
		mAddImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String sdcardState = Environment.getExternalStorageState();
				if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
					showPop();//弹出pop
				} else {
					Toast.makeText(getApplicationContext(), "sdcard已拔出，不能选择照片",
							Toast.LENGTH_SHORT).show();
				}

			}
		});
	}
	

	
	//图片的单个点击事件
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Toast.makeText(this, position+"", 1).show();
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
		.hideSoftInputFromWindow(ContributeActivity.this.getCurrentFocus()
				.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		Intent intent = new Intent(ContributeActivity.this, PhotoSActivity.class);
		intent.putExtra("ID", position+"");
		startActivity(intent);

	}

	// 这个是弹出拍照选择照片的popwindow
	public void showPop(){
		LayoutInflater inflater=LayoutInflater.from(this);
			View view = inflater.inflate(R.layout.edit_photo, null);
			final PopupWindow window = new PopupWindow(view,
					WindowManager.LayoutParams.MATCH_PARENT,
					WindowManager.LayoutParams.WRAP_CONTENT);
			window.setFocusable(true);
			// 设置背景
			ColorDrawable dw = new ColorDrawable(R.color.white);
			window.setBackgroundDrawable(dw);

			// 设置动画
			window.setAnimationStyle(R.style.mypopwindow_anim_style);
			// 设置展现的位置
			window.showAtLocation(findViewById(R.id.contribite),
					Gravity.BOTTOM, 0, 0);
			view.findViewById(R.id.photoGtaph).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							 photo();
							window.dismiss();
						}

						
					});
			view.findViewById(R.id.upload_photo).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent i = new Intent(
									// 相册
									Intent.ACTION_PICK,
									android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						startActivityForResult(i, RESULT_LOAD_IMAGE);
							window.dismiss();

						}
					});
			view.findViewById(R.id.cancle).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					window.dismiss();
				}
			});
			window.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {

				}
			});
		}
//保存图片
	private static final int TAKE_PICTURE = 0;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int CUT_PHOTO_REQUEST_CODE = 2;
	private String path = "";
	private Uri photoUri;
	//拍照处理图片
	private void photo() {
		try {
			Intent openCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);

			String sdcardState = Environment.getExternalStorageState();
			String sdcardPathDir = android.os.Environment
					.getExternalStorageDirectory().getPath() + "/tempImage/";
			File file = null;
			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// 有sd卡，是否有myImage文件夹
				File fileDir = new File(sdcardPathDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 是否有headImg文件
				file = new File(sdcardPathDir + System.currentTimeMillis()
						+ ".JPEG");
			}
			if (file != null) {
				path = file.getPath();
				photoUri = Uri.fromFile(file);
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(openCameraIntent, TAKE_PICTURE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	//这个是一个回调
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			switch (requestCode) {
			case TAKE_PICTURE:
				if (drr.size() < 6 && resultCode == -1) {// 拍照
					startPhotoZoom(photoUri);
					
				}
				break;
			case RESULT_LOAD_IMAGE:
				if (drr.size() < 6 && resultCode == RESULT_OK && null != data) {// 相册返回
					Uri uri = data.getData();
					if (uri != null) {
						startPhotoZoom(uri);
						
					}
				}
				break;
			case CUT_PHOTO_REQUEST_CODE:
				if (resultCode == RESULT_OK && null != data) {// 裁剪返回
					Bitmap bitmap = Bimp.getLoacalBitmap(drr.get(drr.size() - 1));
					PhotoSActivity.bitmap.add(bitmap);
					bitmap = Bimp.createFramedPhoto(480, 480, bitmap,
							(int) ( 1.6f));
					bmp.add(bitmap);
					adapter.setList(bmp);
					adapter.notifyDataSetChanged();
					
				}
				break;
			}
		}
		//这个是对图片进行剪切
		@SuppressLint({ "SdCardPath", "SimpleDateFormat" })
		private void startPhotoZoom(Uri uri) {
			try {
				// 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
				SimpleDateFormat sDateFormat = new SimpleDateFormat(
						"yyyyMMddhhmmss");
				String address = sDateFormat.format(new java.util.Date());
				if (!FileUtils.isFileExist("")) {
					FileUtils.createSDDir("");

				}
				drr.add(FileUtils.SDPATH + address + ".JPEG");
				Uri imageUri = Uri.parse("file:///sdcard/formats/" + address
						+ ".JPEG");

				final Intent intent = new Intent("com.android.camera.action.CROP");

				// 照片URL地址
				intent.setDataAndType(uri, "image/*");

				intent.putExtra("crop", "true");
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 480);
				intent.putExtra("outputY", 480);
				// 输出路径
				intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				// 输出格式
				intent.putExtra("outputFormat",
						Bitmap.CompressFormat.JPEG.toString());
				// 不启用人脸识别
				intent.putExtra("noFaceDetection", false);
				intent.putExtra("return-data", false);
				startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);

			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		protected void onDestroy() {

			FileUtils.deleteDir(FileUtils.SDPATH);
			FileUtils.deleteDir(FileUtils.SDPATH1);
			// 清理图片缓存
			for (int i = 0; i < bmp.size(); i++) {
				bmp.get(i).recycle();
			}
			for (int i = 0; i < PhotoSActivity.bitmap.size(); i++) {
				PhotoSActivity.bitmap.get(i).recycle();
			}
			PhotoSActivity.bitmap.clear();
			bmp.clear();
			drr.clear();
			super.onDestroy();
		}
		  @Override  
		    public boolean onDown(MotionEvent e) {  
		        // TODO Auto-generated method stub  
		        return false;  
		    }  
		  
		    @Override  
		    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,  
		            float velocityY) {  
		        // TODO Auto-generated method stub  
		        return false;  
		    }  
		  
		    @Override  
		    public void onLongPress(MotionEvent e) {  
		        // TODO Auto-generated method stub  
		          
		    }  
		  
		    @Override  
		    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,  
		            float distanceY) {  
		        // TODO Auto-generated method stub  
		        return false;  
		    }  
		  
		    @Override  
		    public void onShowPress(MotionEvent e) {  
		        // TODO Auto-generated method stub  
		          
		    }  
		  
		    @Override  
		    public boolean onSingleTapUp(MotionEvent e) {  
		        // TODO Auto-generated method stub  
		        return false;  
		    }  
		  
		  
		
}
